package com.msh.platform.elm.controller;

import java.io.Serializable;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.msh.platform.elm.common.constants.Constants;
import com.msh.platform.elm.common.util.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;


public class BaseController {
	@Autowired
    private RedisTemplate redisTemplate;
	
	private static Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	/**
	 * 根据token获取用户信息
	 * @param token
	 * @return
	 */
	public Object getUserByToken(String token) {
		ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
		Object tokenValue = operations.get(token);
		resetTokenExpiresTime(token);  //每次操作都重新设置token过期时间
		return tokenValue;
	}

	/**
	 * 校验接口签名
	 * @param paramStr
	 * @param sign
	 * @return
	 */
	public Boolean validateSign(String paramStr, String sign){
		
		logger.info("接口传递签名sign:{}", sign);
		
		logger.info("接口参数加密前:{}", paramStr);
		try {
			String currSign = MD5Utils.md5(paramStr, "utf-8");
			logger.info("接口参数加密后:{}", currSign);
			
			if(StringUtils.isBlank(sign)){
				return false;
			}
			
			if(!StringUtils.isBlank(sign) && currSign.trim().equals(sign.trim())){//sign验证合法
				return true;
			} else {
				return false;
			}
			
		} catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * 重设token过期时间
	 * @param token
	 * @return
	 */
	public void resetTokenExpiresTime(String token) {
		if(StringUtils.isNotBlank(token)) {
    		ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
    		Object tokenValue = operations.get(token);
    		if(tokenValue!=null) {
    			redisTemplate.expire(token, Constants.TOKEN_EXPIRE_TIME, TimeUnit.MINUTES);  //每次操作重新设置token过期时间
    		}
    	}
	}
	
	//生成6位随机验证码
	public static String genRadomNbr() {
		Random random = new Random();
		String result = "";
		for (int i = 0; i < 6; i++) {
			result += random.nextInt(10);
		}
		return result;
	}
	
}
